#include "MainWindow.hpp"
#include "hotkey.hpp"
#include  <string>
static HWND hwndListView = nullptr;


LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam  ) {
    Core* core_instance = reinterpret_cast<Core*>(lParam);
    if (uMsg == core_instance->getDllMessageId()) {
        DWORD proc_id;
        GetWindowThreadProcessId(reinterpret_cast<HWND>(wParam), &proc_id);
        return 0;
    }
    switch (uMsg) {
        case WM_SYSKEYUP: {
            if (wParam == VK_MENU) {
                // 捕获 Alt 键
                return 0; // 阻止默认行为
            }

            // 获取当前按键（例如 Alt+`）
            char keyName[64];
            GetKeyNameText(static_cast<LONG>(lParam), keyName, sizeof(keyName));

            // 构建完整按键名称
            std::string hotkey = "Alt + ";
            hotkey += keyName;

            // 将按键信息添加到 ListView
            LVITEM lvItem = {};
            lvItem.mask = LVIF_TEXT;
            lvItem.iItem = ListView_GetItemCount(hwndListView); // 插入到最后一行
            lvItem.iSubItem = 0;
            lvItem.pszText = const_cast<char*>(hotkey.c_str());
            ListView_InsertItem(hwndListView, &lvItem);
            CHAR buffer[13] = "Key captured";
            ListView_SetItemText(hwndListView, lvItem.iItem, 1, buffer);

            return 0; // 阻止 Alt 的默认行为
        }
        case  WM_CLOSE : {
            core_instance->removeHooks();
            core_instance-> setTerminatingEvent();
            DestroyWindow(hwnd);
            return 0;

        }
        case WM_CREATE: {
            InitListView(hwnd);
            return 0;
        } ;
        case WM_DESTROY: {
            PostQuitMessage(0);
            return 0;
        }
        // case  WM_SIZE : {
        //     if (g_hwndListView) {
        //         ResizeListView( hwnd,  g_hwndListView);
        //     }
        //     return 0;
        // }
        case WM_PAINT: {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hwnd, &ps);
            FillRect(hdc, &ps.rcPaint, reinterpret_cast<HBRUSH>((COLOR_WINDOW + 1))); // 用白色填充窗口
            EndPaint(hwnd, &ps);
        }
        case WM_LBUTTONDBLCLK: { return 0; }
        case WM_RBUTTONDOWN: { return 0; }
        case WM_RBUTTONUP: { return 0; }
        case WM_MBUTTONDOWN: { return 0; }
        case WM_MBUTTONUP: { return 0; }
        case WM_LBUTTONUP: { return 0; }
        case WM_LBUTTONDOWN : { return 0; }

        default: break ;
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}


void InitListView(HWND hwndParent) {
    // 初始化 Common Controls
    INITCOMMONCONTROLSEX icex;  // 结构体变量 icex 用于初始化 Common Controls
    icex.dwSize = sizeof(INITCOMMONCONTROLSEX); // 结构体大小
    icex.dwICC = ICC_LISTVIEW_CLASSES;  //ICC_LISTVIEW_CLASSES是一个预定义的常量，它表示这个窗口类将包含列表视图控件（ListView）的样式。
    InitCommonControlsEx(&icex); // 初始化 Common Controls

    // 创建 ListView 控件
      hwndListView = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        WC_LISTVIEW,
        "",
        WS_VISIBLE | WS_CHILD | LVS_REPORT   ,
        10, 10, 460, 200,
        hwndParent,
        nullptr,
        GetModuleHandle(nullptr),
        nullptr
    );
    // 启用扩展样式，添加网格线
    ListView_SetExtendedListViewStyle(hwndListView, LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);
    // 添加列
    LVCOLUMN lvc = {};
    lvc.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM;

    lvc.pszText = const_cast<LPSTR>("Hotkey");
    lvc.cx = 140 ; // 列宽
    ListView_InsertColumn(hwndListView, 0, &lvc);

    lvc.pszText = const_cast<LPSTR>("Process Path");
    lvc.cx = 310;
    ListView_InsertColumn(hwndListView, 1, &lvc);

    // 添加行数据
    LVITEM lvi = {};
    lvi.mask = LVIF_TEXT | LVCF_WIDTH ;




     lvi.pszText = const_cast<LPSTR>("Win + E ");
    lvi.iItem = 0;
    ListView_InsertItem(hwndListView, &lvi);

    ListView_SetItemText(hwndListView, 0, 1, const_cast<LPSTR>("C:\\WINDOWS\\explorer.exe"));

}

void ResizeListView(HWND hwndParent , HWND g_hwndListView) {
    if (g_hwndListView) {
        // 获取父窗口的客户区大小
        RECT rcClient;
        GetClientRect(hwndParent, &rcClient);

        // 调整 ListView 的大小以填充客户区
        SetWindowPos(g_hwndListView, nullptr,
                     rcClient.left, rcClient.top,
                     rcClient.right - rcClient.left,
                     rcClient.bottom - rcClient.top,
                     SWP_NOZORDER);
    }
}


void   processKeyDownEvent(UINT message, WPARAM wParam, LPARAM lParam, UINT proc_id) {
    bool ctrlPressed = GetAsyncKeyState(VK_CONTROL) & 0x8000;
    bool altPressed = GetAsyncKeyState(VK_MENU ) & 0x8000;
    bool shiftPressed = GetAsyncKeyState(VK_SHIFT) & 0x8000;


    switch ( message) {
        case WM_SYSKEYUP  : {
            if (wParam == VK_MENU) {
                // Alt 键被按下
                bool ctrl_pressed = GetAsyncKeyState(VK_CONTROL) & 0x8000;
                bool shift_pressed = GetAsyncKeyState(VK_SHIFT) & 0x8000;
                // 构建热键名称
                std::string hotkey = "Alt";
                if (ctrl_pressed) hotkey = "Ctrl + " + hotkey;
                if (shift_pressed) hotkey += " + Shift";

                // 获取主键名称
                char keyName[64];
                GetKeyNameText((lParam & 0x01FF0000) >> 16, keyName, sizeof(keyName));
                hotkey += " + ";
                hotkey += keyName;

                // 添加到 ListView
                LVITEM lvItem = {};
                lvItem.mask = LVIF_TEXT;
                lvItem.iItem = ListView_GetItemCount(hwndListView); // 插入到最后一行
                lvItem.iSubItem = 0;
                lvItem.pszText = const_cast<char*>(hotkey.c_str());
                ListView_InsertItem(hwndListView, &lvItem);
                CHAR buffer[13] = "Key captured";
                ListView_SetItemText(hwndListView, lvItem.iItem, 1, buffer);
            }
            return ; // 阻止默认行为
        }
        default: ;
    }
    // 捕获当前按下的键
    // if (wParam != VK_CONTROL && wParam != VK_MENU && wParam != VK_SHIFT) {
        // 构建热键文本
        std::string hotkey;
        if (ctrlPressed) {
            hotkey += "Ctrl + " ;
        };
        if (altPressed) hotkey += "Alt + ";
        if (shiftPressed) hotkey += "Shift + ";

        // 获取按键名称
    if (wParam != VK_CONTROL && wParam != VK_MENU && wParam != VK_SHIFT) {

        char keyName[64];
        GetKeyNameText(MapVirtualKey(wParam, MAPVK_VK_TO_VSC) << 16, keyName, sizeof(keyName));
        hotkey += keyName;
        if ( altPressed) {
            auto  process_path =    Core::getProcessPathByHook( proc_id) ;


            LVITEM lvItem = {};
            lvItem.mask = LVIF_TEXT;
            lvItem.iItem = ListView_GetItemCount(hwndListView); // 插入到最后一行
            lvItem.iSubItem = 0;
            lvItem.pszText = const_cast<char*>(hotkey.c_str());
            ListView_InsertItem(hwndListView, &lvItem);


            int size_needed = WideCharToMultiByte(CP_UTF8, 0, process_path.c_str(), -1, nullptr,
                0, nullptr, nullptr);
            std::string str(size_needed, 0);
            WideCharToMultiByte(CP_UTF8, 0, process_path.c_str(), -1, &str[0],
                size_needed, nullptr, nullptr);

            LPSTR lpstr  = const_cast<LPSTR>(str.c_str())   ;
            // 添加描述列
            ListView_SetItemText(hwndListView, lvItem.iItem, 1,lpstr)

        }else if (ctrlPressed) {
            auto  process_path =    Core::getProcessPathByHook( proc_id) ;


            LVITEM lvItem = {};
            lvItem.mask = LVIF_TEXT;
            lvItem.iItem = ListView_GetItemCount(hwndListView); // 插入到最后一行
            lvItem.iSubItem = 0;
            lvItem.pszText = const_cast<char*>(hotkey.c_str());
            ListView_InsertItem(hwndListView, &lvItem);


            int size_needed = WideCharToMultiByte(CP_UTF8, 0, process_path.c_str(), -1, nullptr, 0, nullptr, nullptr);
            std::string str(size_needed, 0);
            WideCharToMultiByte(CP_UTF8, 0, process_path.c_str(), -1, &str[0], size_needed, nullptr, nullptr);

            LPSTR lpstr  = const_cast<LPSTR>(str.c_str())   ;
            // 添加描述列
            ListView_SetItemText(hwndListView, lvItem.iItem, 1,lpstr);
        }else if (shiftPressed) {
             auto   process_path =     Core::getProcessPathByHook( proc_id) ;

            LVITEM lvItem = {};
            lvItem.mask = LVIF_TEXT;
            lvItem.iItem = ListView_GetItemCount(hwndListView); // 插入到最后一行
            lvItem.iSubItem = 0;
            lvItem.pszText = const_cast<char*>(hotkey.c_str());
            ListView_InsertItem(hwndListView, &lvItem);


            int size_needed = WideCharToMultiByte(CP_UTF8, 0,  process_path.c_str() ,  -1, nullptr, 0, nullptr, nullptr);
            std::string str(size_needed, 0);
            WideCharToMultiByte(CP_UTF8, 0,  process_path.c_str()  , -1, &str[0], size_needed, nullptr, nullptr);

            LPSTR lpstr  = const_cast<LPSTR>(str.c_str())   ;
            // 添加描述列
            ListView_SetItemText(hwndListView, lvItem.iItem, 1,lpstr);
        }
    }
}
